/*
 * Copyright 2016. chenshufei
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package sz.szsmk.citizencard.util;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import anet.channel.util.StringUtils;

public class CommonUtils {

  /**
   * 从Assets资源文件中，获取文件流数据...
   *
   * @param context
   * @param fileName
   * @return
   */
  public static byte[] getAssetsFileDate(Context context, String fileName) {
    AssetManager am = context.getResources().getAssets();
    InputStream is = null;
    try {
      is = am.open(fileName);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] buf = new byte[1024];
      int len = -1;
      while ((len = is.read(buf)) != -1) {
        bos.write(buf, 0, len);
      }
      is.close();
      return bos.toByteArray();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }

  }

  /**
   * 获得网络连接是否可用
   *
   * @param context
   * @return
   */
  public static boolean hasNetwork(Context context) {
    ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo workinfo = con.getActiveNetworkInfo();
    if (workinfo == null || !workinfo.isAvailable()) {
      return false;
    } else {
      return true;
    }
  }

  public static String getJson(Context context, String fileName){
    StringBuilder stringBuilder = new StringBuilder();
    //获得assets资源管理器
    AssetManager assetManager = context.getAssets();
    //使用IO流读取json文件内容
    try {
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
              assetManager.open(fileName),"utf-8"));
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return stringBuilder.toString();
  }

  /**
   * 正则表达式 判断电话号是否正确
   */
    /*public static boolean isPhoneHomeNum(String num) {
        String regPhoneNum = XZCityCardApp.getInstance().getResources().getString(R.string.reg_regex_phonenum);
        Pattern p = Pattern.compile(regPhoneNum);
        Matcher m = p.matcher(num);
        return m.matches();
    }

    public static String getString(int stringId){
        return XZCityCardApp.getInstance().getResources().getString(stringId);
    }*/

  /**
   * 距离m转化为km
   *
   * @param meterStr 距离(m)
   * @return
   */
  public static String getStringMeter2KM(int meterStr) {
    if (meterStr <= 1000) {
      return meterStr + "m";
    } else {
      int limit = 50 * 1000;
      if (meterStr <= limit) {
        DecimalFormat df = new DecimalFormat("0.0");
        Double floatDistance = (Double) (meterStr / 1000.00);
        return df.format(floatDistance) + "km";
      } else {
        return meterStr / 1000 + "km";
      }

    }
  }

  /**
   * 校验银行卡卡号
   *
   * @param cardId
   * @return
   */
  public static boolean checkBankCard(String cardId) {
    char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
    if (bit == 'N') {
      return false;
    }
    return cardId.charAt(cardId.length() - 1) == bit;
  }

  /**
   * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
   *
   * @param nonCheckCodeCardId
   * @return
   */
  private static char getBankCardCheckCode(String nonCheckCodeCardId) {
    if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
            || !nonCheckCodeCardId.matches("\\d+")) {
      //如果传的不是数据返回N
      return 'N';
    }
    char[] chs = nonCheckCodeCardId.trim().toCharArray();
    int luhmSum = 0;
    for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
      int k = chs[i] - '0';
      if (j % 2 == 0) {
        k *= 2;
        k = k / 10 + k % 10;
      }
      luhmSum += k;
    }
    return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
  }

  public static void showKeyInput(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {

      @Override
      public void run() {
        ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(editText, 0);
        editText.setSelection(editText.getText().length());
      }
    }, 200);
  }
  public static Drawable getRecCorner(int stockColor,int stockWidth, int solidColor, int leftRadius, int rightRadius) {
    GradientDrawable drawable = new GradientDrawable();
    float[] radius = new float[]{leftRadius,leftRadius, rightRadius, rightRadius, rightRadius,rightRadius, leftRadius,leftRadius};
    drawable.setShape(GradientDrawable.RECTANGLE);
    drawable.setCornerRadii(radius);
    drawable.setStroke(stockWidth, stockColor);
    drawable.setColor(solidColor);
    return drawable;
  }
  public static Drawable getRecCorner(int stockColor, int solidColor, int leftRadius, int rightRadius) {
    return getRecCorner(stockColor,1, solidColor, leftRadius, rightRadius);
  }
  public static StateListDrawable getCheckedSelector(Context context, Drawable checkedDrawable, Drawable normalDrawable) {
    StateListDrawable bg = new StateListDrawable();
    bg.addState(new int[] { android.R.attr.state_checked }, checkedDrawable);
    bg.addState(new int[] { android.R.attr.state_pressed }, normalDrawable);
    bg.addState(new int[] {}, normalDrawable);
    return bg;
  }

  /****
   * 字符串数字转double类型
   * @param d
   * @return
   */
    /*public static double getDouble(String d){
        if(StringUtils.isBlank(d)){
            return 0;
        }
        try {
            return Double.valueOf(d);
        } catch (NumberFormatException e) {
            return 0;
        }
    }*/

  public static long getLong(String d){
    if(StringUtils.isBlank(d)){
      return 0;
    }
    try {
      return Long.valueOf(d);
    } catch (NumberFormatException e) {
      return 0;
    }
  }

    /*public static int getInt(String d){
        if(StringUtils.isBlank(d)){
            return 0;
        }
        try {
            return Integer.valueOf(d);
        } catch (NumberFormatException e) {
            try {
                double rtn = Double.valueOf(d);
                return (int)rtn;
            } catch (NumberFormatException e1) {
                return 0;
            }
        }
    }*/

  /**
   * 验证输入的邮箱格式是否符合
   * @param email
   * @return
   */
  public static boolean emailFormat(String email) {
    boolean tag = true;
    final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    final Pattern pattern = Pattern.compile(pattern1);
    final Matcher mat = pattern.matcher(email);
    if (!mat.find()) {
      tag = false;
    }
    return tag;
  }

   /* public static boolean bindCardCheckNoAutoTip(final Context context){
        boolean isBind = false;
        User user = GlobalVariables.getInstance().getUser();
        UserExtend userExtend = user.getUserExtend();
        String cityCardNo = null;
        if (userExtend != null) {
            cityCardNo = userExtend.getCityCardNo();
            if (!TextUtils.isEmpty(cityCardNo)) {  //有市民卡
                isBind = true;
            }
        }else {
            isBind = false;
        }
        return isBind;
    }*/


  /**
   * 给TextView 加下划线
   * @param textView
   */
  public static void textViewAddUnderLine(TextView textView){
    textView.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线
    textView.getPaint().setAntiAlias(true);//抗锯齿
  }

  /**
   * 获取32位的md5
   * @param plainText
   * @return
   */
  public static String toMD5(String plainText) {
    try {
      //生成实现指定摘要算法的 MessageDigest 对象。
      MessageDigest md = MessageDigest.getInstance("MD5");
      //使用指定的字节数组更新摘要。
      md.update(plainText.getBytes());
      //通过执行诸如填充之类的最终操作完成哈希计算。
      byte b[] = md.digest();
      //生成具体的md5密码到buf数组
      int i;
      StringBuffer buf = new StringBuffer("");
      for (int offset = 0; offset < b.length; offset++) {
        i = b[offset];
        if (i < 0)
          i += 256;
        if (i < 16)
          buf.append("0");
        buf.append(Integer.toHexString(i));
      }
      return buf.toString(); // 32位的加密
      //System.out.println("32位: " + buf.toString());// 32位的加密
      //System.out.println("16位: " + buf.toString().substring(8, 24));// 16位的加密，其实就是32位加密后的截取
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }

  public static String getVerifyCode(String phone){
    String md5Code = toMD5("FINANCE_"+phone);
    StringBuilder str=new StringBuilder();//定义变长字符串
    Random random=new Random();
    //随机生成数字，并添加到字符串
    for(int i=0;i<8;i++){
      str.append(random.nextInt(10));
    }
    String eightStr = str.toString();
    String part1 = eightStr.substring(0, 2)+md5Code.substring(0, 8);
    String part2 = eightStr.substring(2, 4)+md5Code.substring(8, 16);
    String part3 = eightStr.substring(4, 6)+md5Code.substring(16, 24);
    String part4 = eightStr.substring(6, 8)+md5Code.substring(24, 32);
    String retVal = part1+part2+part3+part4;
    return retVal;
  }



}
